package com.uum.auth.security.service.userdetails;

import com.uum.admin.api.UserFeignClient;
import com.uum.admin.dto.UserAuthDTO;
import com.uum.common.core.result.Result;
import com.uum.common.core.result.ResultCode;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 系统用户体系业务类
 *
 */
@Service("sysUserDetailsService")
@RequiredArgsConstructor
public class SysUserDetailsServiceImpl implements UserDetailsService {

    private final UserFeignClient userFeignClient;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUserDetails userDetails = null;
        //feign远程调用uum-admin服务获取用户信息
        Result<UserAuthDTO> result = userFeignClient.getUserByUsername(username);
        if (Result.isSuccess(result)) {
            UserAuthDTO user = result.getData();
            if (null != user) {
                userDetails = new SysUserDetails(user);
            }
        }
        if (userDetails == null) {
            throw new UsernameNotFoundException(ResultCode.USER_NOT_EXIST.getMsg());
        } else if (!userDetails.isEnabled()) {
            throw new DisabledException(ResultCode.USER_ACCOUNT_UNENABLED.getMsg());
        } else if (!userDetails.isAccountNonLocked()) {
            throw new LockedException(ResultCode.USER_ACCOUNT_LOCKED.getMsg());
        }
        return userDetails;
    }

}
